package com.thprojects.myphotomemories.view;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.DbController;
import com.thprojects.myphotomemories.controller.FSController;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.model.Album;
import com.thprojects.myphotomemories.model.Photo;
import com.thprojects.myphotomemories.view.components.PhotoAdapter;

import exception.PhotoSourceNotFoundException;
import exception.SDNotReadyException;

public class AlbumView extends Activity {
	
	private final static int FILE_REQUEST = 1000;
	private final static int CAMERA_REQUEST = 1001;
	
	FSController mFSController;
	DbController mDbController;
	ProgressDialog mPDialog;
	List<Photo> mPhotos;
	Album mAlbum;
	Gallery mGallery;
	TextView mEmptyAlbum;
	ImageView mPhotoPreview;
	int mPreviewWidth, mPreviewHeight;
	Uri mFileDest;

	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.album_view);
        
        Intent i = getIntent();
        mAlbum = (Album) i.getParcelableExtra("album");
        
        
        mGallery = (Gallery)findViewById(R.id.photo_gallery);
		mGallery.setSpacing(0);
		
		mPhotoPreview = (ImageView)findViewById(R.id.photo_preview);
		mEmptyAlbum = (TextView)findViewById(R.id.empty_album);

		mFSController = FSController.getFSController(this);
		
		TextView tName = (TextView)findViewById(R.id.album_view_name);
		tName.setText(mAlbum.getName());
		TextView tDescr = (TextView)findViewById(R.id.album_view_descr);
		tDescr.setText(mAlbum.getDescription());

		//load photos
        LoadPhotosTask at = new LoadPhotosTask();
        at.execute(this);
    }
    
    @Override
    public void onRestart(){
    	super.onRestart();
    	//load photos
        LoadPhotosTask at = new LoadPhotosTask();
        at.execute(this);
    }
    
    private void showPhoto(){
    	GuiController.showPhoto(this, (Photo)mGallery.getSelectedItem());
    }
    
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuItem mi1 = menu.add("Add from Camera");
		mi1.setIcon(R.drawable.menu_new_camera);		
		mi1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			
			public boolean onMenuItemClick(MenuItem item) {
				getImageFromCamera();
				return false;
			}
		});
		
		MenuItem mi2 = menu.add("Add from File");
		mi2.setIcon(R.drawable.menu_new_file);
		mi2.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			
			public boolean onMenuItemClick(MenuItem item) {
				getImageFromFile();
				return false;
			}
		});
		
		return true;
	}
    
    private void showDialog(){
    	mPDialog = ProgressDialog.show(this, "", "Loading photos...", true);
    }

    private void showPhotoList(){
    	if (mPhotos.size() == 0){
    		mPhotoPreview.setVisibility(View.INVISIBLE);
    		mEmptyAlbum.setVisibility(View.VISIBLE);
    	}
    	else{
    		mPhotoPreview.setVisibility(View.VISIBLE);
    		mEmptyAlbum.setVisibility(View.INVISIBLE);
    		mGallery.setOnItemClickListener(new OnItemClickListener() {
    	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    	        	setPreview(position);
    	        }
    	    });
    		
    		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

    			public void onItemSelected(AdapterView<?> arg0, View arg1,  int arg2, long arg3) {
    				setPreview(arg2);	
    			}

    			public void onNothingSelected(AdapterView<?> arg0) {
    				setPreview(0);
    			}
    			
    		});
    		
    		mPhotoPreview.setOnClickListener(new OnClickListener() {			
    			public void onClick(View v) {
    				showPhoto();
    			}
    		});
    		mGallery.setAdapter(new PhotoAdapter(this, mPhotos, mGallery.getMeasuredHeight()));
    		setPreview(0);  
    	}
		
    }
    
    private void setPreview (int idx){
		mPreviewHeight = mPhotoPreview.getMeasuredHeight();
		mPreviewWidth = mPhotoPreview.getMeasuredWidth();
		Bitmap bmp;
		try {
			bmp = mFSController.decodeSampledBitmap(mPhotos.get(idx).getPath(), mPreviewWidth, mPreviewHeight);
			mPhotoPreview.setImageBitmap(bmp);
		} catch (PhotoSourceNotFoundException e) {
		} catch (SDNotReadyException e) {
		}
    	
	}
    
    
    private class LoadPhotosTask extends AsyncTask<Context, Void, List<Photo>>{

		@Override
		protected List<Photo> doInBackground(Context... params) {
			mDbController = DbController.getDbController(params[0]);
			return mDbController.getPhotoList(mAlbum);
		}
	
		@Override
		protected void onPostExecute(List<Photo> result) {
			super.onPostExecute(result);
			mPhotos = result;
			mPDialog.dismiss();
			showPhotoList();
		}
	
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog();
		}
    	
    }

    
    //get an image from camera
    private void getImageFromCamera(){
    	Log.d("MPM", "gettingImageFromCamera");
    	Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 

    	//url where to put new img
    	File path = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        Log.d("MPM","path: "+path);
        File file = new File(path, mFSController.getTimeStamp()+".jpg");
        mFileDest = Uri.fromFile(file);
    	cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,  mFileDest);
    	
        startActivityForResult(cameraIntent, CAMERA_REQUEST); 
    }
    
    // get an image from file system
 	private void getImageFromFile(){
 		Log.d("MPM", "gettingImageFromFile");
 		Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
 		fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
 		fileIntent.setType("image/*");
 		this.startActivityForResult(Intent.createChooser(fileIntent, "Choose a photo"), FILE_REQUEST); 
 	}
 	
 	
	/* called when the result is available */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == FILE_REQUEST && resultCode == RESULT_OK) {
			if (data == null){
				GuiController.showError(this, "An error has occurred. Please try again.");
				return;
			}
				
			// obtain the filename
			Uri uri = data.getData();
			String filePath = null;
			if (uri != null) {
				if (uri.toString().startsWith("file:")) {
					filePath = uri.getPath();
				} else { // uri.startsWith("content:")
					Cursor c = getContentResolver().query(uri, null, null,
							null, null);
					if (c != null && c.moveToFirst()) {
						int id = c.getColumnIndex(Images.Media.DATA);
						if (id != -1) {
							filePath = c.getString(id);
						}
					}
				}
			}
			
			if (filePath == null){
				GuiController.showError(this, "An error has occurred. Please try again.");
				return;
			}
			
			String fp;
			try {
				fp = mFSController.saveImageCopy(filePath);
				addPhoto(fp);
			} catch (SDNotReadyException e) {
				GuiController.showError(this, e.getMessage());
			}			
			

		}

		else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {			
			Log.d("MPM", "mFileDest path="+mFileDest.getPath());
			addPhoto(mFileDest.getPath());
		}
	}
	
     
     private void addPhoto(String filePath){
      	Log.d("MPM", filePath);
     	GuiController.showPhotoDetails(this, filePath, mAlbum);
     }
     
}
